<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2018 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 小夏 < 449134904@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use app\admin\model\DeviceModel;
use app\admin\model\DeviceUserModel;
use app\user\model\UserCurrentDeivceModel;
use cmf\controller\AdminBaseController;
use think\Db;

class DeviceController extends AdminBaseController
{

    /**
     * 幻灯片列表
     * @adminMenu(
     *     'name'   => '幻灯片管理',
     *     'parent' => 'admin/Setting/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 40,
     *     'icon'   => '',
     *     'remark' => '幻灯片管理',
     *     'param'  => ''
     * )
     */
    public function index()
    {
        $DeviceModel = new DeviceModel();
        $request = input('request.');
        $where = array();
        if(isset(input()['type']) && input()['type'] == 'user'){
            $id = input()['id'];
            $where['erxi_device_user.uid'] = $id;
        }
        if (!empty($request['keyword'])) {
            $keyword = $request['keyword'];
            $where['erxi_device.imei'] = ['like', "%$keyword%"];
        }
        $list = $DeviceModel
            ->join("erxi_device_user", "erxi_device.imei=erxi_device_user.imei", "left")
            ->join("erxi_user", " erxi_user.id=erxi_device_user.uid", "left")
            ->field("erxi_device.*,erxi_user.user_nickname username, erxi_device_user.uid user_id, erxi_device_user.device_id")
            ->where($where)->paginate(10);
            // echo Db::table("erxi_device")->getLastSql();die;
        $page = $list->render();
        $this->assign('list', $list);
        $this->assign('page', $page);

        return $this->fetch();
    }

    public function add()
    {
        return $this->fetch();
    }

    public function edit()
    {
        $data = $this->request->param();
        $id = $data['id'];
        $model = new DeviceModel();
        $device = $model->find($id);
        $device['effect_time'] = date("Y-m-d",$device['effect_time']);
        $this->assign('device', $device);
        return $this->fetch();
    }

    public function editdevice()
    {
        if ($this->request->isPost()) {
            $data = $this->request->param();
            $model = new DeviceModel();
            $data['post']['effect_time'] = strtotime($data['post']['effect_time']);
            $model->where(['id' => $data['post']['id']])->update($data['post']);
            $this->success('修改成功!', url('admin/device/index'));
        }
    }

    public function deleteDevice()
    {
        $id = $data = $this->request->param("id");
        $model = new DeviceModel();
        $model->where(['id' => $id])->delete();
        $DeviceUserModel = new DeviceUserModel();
        $DeviceUserModel->where(['device_id'=>$id])->delete();
        $this->success('删除成功!', url('admin/device/index'));
    }
    
    // 接触用户绑定设备
	public function unbindDevice() {
		$uid = $this->request->param("uid", 0, "intval");
		$device_id = $this->request->param("device_id", 0, "intval");
		if ($uid == 0 || $device_id == 0) {
            $this->error('参数错误!');
		}
		$data = [
			'device_id' => $device_id,
			'uid' => $uid,
		];
		$duModel = new DeviceUserModel();
		$usercurrentdevice = new UserCurrentDeivceModel();
		$usercurrentdevice->where([
			'uid' => $uid,
			'd_id' => $device_id,
		])->delete();
		$device_user = $duModel->where($data)->find();
		if (!$device_user) {
            $this->error('设备没有被绑定');
		}
		$device_user->delete();
        $this->success('解除绑定成功', url('admin/device/index'));
        
	}

    public function adddevice()
    {
        if ($this->request->isPost()) {
            $model = new DeviceModel();
            $data = $this->request->param();
            $imei = $data['post']['imei'];
            $back = $model->where(['imei'=>$imei])->count();
            if($back>0){
                $this->error('设备已添加!');
            }
            $data['post']['effect_time'] = strtotime($data['post']['effect_time']);
            $id = $model->insert($data['post']);
//            $post   = $data['post'];
            //            $result = $this->validate($post, 'AdminArticle');
            //            if ($result !== true) {
            //                $this->error($result);
            //            }

//            $portalPostModel = new PortalPostModel();
            //
            //            if (!empty($data['photo_names']) && !empty($data['photo_urls'])) {
            //                $data['post']['more']['photos'] = [];
            //                foreach ($data['photo_urls'] as $key => $url) {
            //                    $photoUrl = cmf_asset_relative_url($url);
            //                    array_push($data['post']['more']['photos'], ["url" => $photoUrl, "name" => $data['photo_names'][$key]]);
            //                }
            //            }
            //
            //            if (!empty($data['file_names']) && !empty($data['file_urls'])) {
            //                $data['post']['more']['files'] = [];
            //                foreach ($data['file_urls'] as $key => $url) {
            //                    $fileUrl = cmf_asset_relative_url($url);
            //                    array_push($data['post']['more']['files'], ["url" => $fileUrl, "name" => $data['file_names'][$key]]);
            //                }
            //            }
            //
            //            $portalPostModel->adminAddArticle($data['post'], $data['post']['categories']);
            //
            //            $data['post']['id'] = $portalPostModel->id;
            //            $hookParam          = [
            //                'is_add'  => true,
            //                'article' => $data['post']
            //            ];
            //            hook('portal_admin_after_save_article', $hookParam);

            $this->success('添加成功!', url('admin/device/index'));
        }
    }
}
